package http_api

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/accesslog"
	"lib/app"
	"lib/bootstrap/jsonrpc_api"
	"lib/exception"
	"lib/logger"
)

func apiLoggingHandler(app *iris.Application) (string, exception.Exception) {
	log := accesslog.File("api-access.log")
	log.Delim = '|'
	log.TimeFormat = "2006-01-02 15:04:05"
	log.Async = false
	log.IP = true
	// TODO: be careful of saving request and response body
	log.BytesReceivedBody = true
	log.BytesSentBody = true
	log.BytesReceived = true
	log.BytesSent = true
	log.BodyMinify = true
	log.RequestBody = true
	log.ResponseBody = true
	log.KeepMultiLineError = true
	log.PanicLog = accesslog.LogHandler
	log.SetFormatter(&accesslog.JSON{
		Indent:    "  ",
		HumanTime: true,
	})
	app.UseRouter(log.Handler)
	return "access log", nil
}

func HttpApiBootstrap() {
	irisApplication := app.Instance().Instance()
	for _, f := range []func(application *iris.Application) (string, exception.Exception){
		apiLoggingHandler,
		jsonrpc_api.JsonRpcApiHandler,
	} {
		module, err := f(irisApplication)
		if err != nil {
			logger.Errorf("Failed to register http api for module %v. Err is %v.", module, err)
		} else {
			logger.Infof("Register http api for module %v.", module)
		}
	}
}
